<!--设备领用界面-->
<template>

<!--  当前患者: {{patient?.patId}} {{isStringEmpty(patient?.patName)?'无':patient.patName}}-->

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="检查项目" prop="">
        {{formData.checkType && checkTypeStore.getCheckTypeName(formData.checkType)}}
      </el-form-item>
      <el-form-item label="患者编号" prop="patId">
        <el-input v-model="formData.patId" placeholder="请输入患者编号" @input="getRentInfoByPatId" />
        <Barcode v-if="displayBarCode" :value="displayBarCode" :width=100 />
        <el-button @click="copyBarcode()">复制</el-button>
      </el-form-item>
      <el-form-item label="患者名称" prop="patName">
        <el-input v-model="formData.patName" placeholder="请输入患者名称" />
      </el-form-item>

      <el-form-item label="患者描述" prop="patDeptDesc">
        <dict-tag v-if="formData.patSrc" :type="DICT_TYPE.ECG_PAT_SOURCE" :value="formData.patSrc" />
        {{formData.patDetails?.deptDesc}} {{formData.patDetails?.wardDesc}} {{formData.patDetails?.bedNo}}
      </el-form-item>
      <el-form-item label="设备编号" prop="devId">
        <el-input v-model="formData.devId" placeholder="请输入设备编号" @input="getDevInfo"/>
      </el-form-item>
      <el-form-item label="设备描述" prop="">
        {{deviceInfo.brand + "&nbsp;&nbsp;" + deviceInfo.model + " " + deviceInfo.state}}
      </el-form-item>
      <el-form-item label="领用时间" prop="rentTime">
        <el-date-picker
          v-model="formData.rentTime"
          type="date"
          value-format="x"
          placeholder="选择领用时间"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
<!--
      <el-form-item label="缴费确认" prop="paid">
        <el-radio-group v-model="formData.paid">
          <el-radio key="1" :label="1"> 已缴费 </el-radio>
          <el-radio key="0" :label="0"> 未缴费 </el-radio>
        </el-radio-group>
      </el-form-item>
-->
    </el-form>
    <el-button @click="submitForm" type="primary" :disabled="formLoading">领用完成</el-button>
    <el-checkbox style="margin-left:10px" label="自动&nbsp;" v-model="autoPrint" />
    <el-button @click="printBill(formData.patId!, formData.checkType!)">打印小票</el-button>
    <el-button @click="printBill(formData.patId!, formData.checkType!, 8)">打印小票2</el-button>
    <el-button @click="cancelReady"  :disabled="formLoading">放弃领用</el-button>
    <el-button @click="resetForm()">重 置</el-button>
    <el-button v-if="formData.checkType && checkTypeStore.getExpenseRecognition(formData.checkType)" @click="feeConfirm"  :disabled="formLoading">确费</el-button>
    <el-button v-if="formData.checkType && checkTypeStore.getExpenseRecognition(formData.checkType)" @click="feeCancel"  :disabled="formLoading">取消确费</el-button>

  <!-- 医生装机列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" @row-click="onRowClick" >
<!--      <el-table-column label="id" align="center" prop="id" />-->
      <el-table-column label="确费" align="center" prop="paid">
        <template #default="scope">
          {{scope.row.paid == 1 ? "已确费" : ""}}
        </template>
      </el-table-column>
      <el-table-column label="领用情况" align="center" prop="cancelled" >
        <template #default="scope">
          <span v-if="scope.row.jobType === 5">"已领用"</span>
          <span v-if="scope.row.jobType === 30">"已放弃"</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="作业类型" align="center" prop="jobType" />-->
<!--      <el-table-column label="医生编号" align="center" prop="docId" />-->
      <el-table-column label="医生名称" align="center" width="auto" prop="docName" />
      <el-table-column label="设备编号" align="center" prop="devId" />
<!--      <el-table-column label="患者编号" align="center" prop="patId" />-->
      <el-table-column label="患者名称" align="center" prop="patName" />
      <el-table-column
          label="作业时间"
          align="center"
          prop="jobTime"
          :formatter="dateFormatter"
          width="180px"
      />
<!--      <el-table-column label="作业概要" align="center" prop="summary" />-->
      <el-table-column label="备注" align="center" prop="remark" />
<!--
      <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
      />
-->
<!--
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['ecg:job-record:update']"
          >
            编辑
          </el-button>
          <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['ecg:job-record:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
-->
    </el-table>
    <!-- 分页 -->
    <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </ContentWrap>

</template>

<script setup lang="ts">
import {defineComponent, PropType} from "vue";
import {Barcode} from "@/components/Barcode";
import { DevRentApi, DevRentVO } from '@/api/ecg/devrent'
import {QueueVO} from "@/api/ecg/queue";
import {isStringEmpty} from "@/utils/stringUtil";
import {dateFormatter} from "@/utils/formatTime";
import {JobRecordApi, JobRecordVO} from "@/api/ecg/jobrecord";
import {DeviceApi, DeviceVO} from "@/api/ecg/devmanage";
import {calculateAge, curDayEnd, curDayStart, formatTimestamp} from "@/utils/dateUtil";
import {RoomBedVO} from "@/api/ecg/doctor";
import {hiprint} from "vue-plugin-hiprint";
import {AppointmentApi, AppointmentVO} from "@/api/ecg/appointment";
import {useCheckTypeStore} from '@/store/modules/checkType'
import {calGender, getBookBeginTime} from "@/utils";
import form from "@/components/Form/src/Form.vue";
import {DICT_TYPE} from "@/utils/dict";

/** 设备领用 表单 */
defineComponent({ name: 'DevReadyPanel' })

const  props = defineProps({
  room: {
    type: Object as PropType<RoomBedVO>,
    required: true
  }
})

const emit = defineEmits(['event_dev_ready']) // 定义 success 事件，用于操作成功后的回调

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const autoPrint = ref<boolean>(true);

const checkTypeStore = useCheckTypeStore()

const formData = ref<DevRentVO>({
  id: undefined,
  devId: undefined,
  patId: undefined,
  patName: undefined,
  patDetails: undefined,
  checkType: undefined,
  rentTime: new Date().getTime(),
  returnTime: undefined,
  interference: undefined,
  baseline: undefined,
  detachment: undefined,
  remark: undefined,
  paid: undefined,
  roomId: props.room.roomId,
  bedNo: props.room.bedNo
})

const formRules = reactive({
  devId: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }],
  rentTime: [{ required: true, message: '请选择装机日期', trigger: 'blur' }],
  patId: [{ required: true, message: '目前没有患者', trigger: 'blur' }],
  patName: [{ required: true, message: '目前没有患者', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const deviceInfo = ref<DeviceVO> ({
  id: 0,
  devId: '',
  category: '',
  brand: '',
  model: '',
  purchaseDate: 0,
  state: 0,
})

const displayBarCode = ref<string> ()

const getRentInfoByPatId = () => {
  const tempPatId = formData.value.patId;
  resetForm()
  if (isStringEmpty(tempPatId))
    return

  formData.value.patId = tempPatId;
  getFreeRentInfo(formData.value)
  copyBarcode()
}

// 根据患者或设备, 获取 Free的租赁
const getFreeRentInfo = async (devRentVO) => {
  const data = await DevRentApi.getFreeRent(devRentVO)
  if (null === data)
    return

  // formDate 对应  DevRent
  // formData.value = data  //不能整个赋值， 默认领用时间被清空
  formData.value.id = data.id;   //rent id
  formData.value.applyNo = data.applyNo;
  formData.value.episodeId = data.episodeId;
  formData.value.patDetails = data.patDetails
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    formData.value.roomId = props.room.roomId
    formData.value.bedNo = props.room.bedNo
    const data = formData.value
    console.info( data )

    await DevRentApi.devReady(data)

    if (autoPrint.value)
      printBill( data.patId, data.checkType)

    dialogVisible.value = false
    // 发送操作成功的事件
    emit('event_dev_ready')
    resetForm()
    getList()

    message.success(t('操作完成'))
  } finally {
    formLoading.value = false
  }
}

// 放弃领用
const cancelReady = async () => {
  formData.value.roomId = props.room.roomId
  formData.value.bedNo = props.room.bedNo
  const data = formData.value as unknown as DevRentVO

  await DevRentApi.devReadyCancel(data)
  message.success(t('操作成功'))

  // 发送操作成功的事件
  emit('event_dev_ready')
  resetForm()
  getList()
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    devId: undefined,
    patId: undefined,
    patName: undefined,
    checkType: undefined,
    rentTime: new Date().getTime(),
    returnTime: undefined,
    interference: undefined,
    baseline: undefined,
    detachment: undefined,
    remark: undefined,
    patDetails: undefined,
    paid: undefined,
    roomId: props.room.roomId,
    bedNo: props.room.bedNo
  }
  formRef.value?.resetFields()

  deviceInfo.value.category = ''
  deviceInfo.value.brand = ''
  deviceInfo.value.model = ''
  deviceInfo.value.state = 0
}

const setPatient = (queueVO: QueueVO | undefined) => {
  resetForm()
  formData.value.applyNo = queueVO?.applyNo
  formData.value.episodeId = queueVO?.episodeId
  formData.value.patId = queueVO?.patId
  formData.value.patName = queueVO?.patName
  formData.value.checkType = queueVO?.bookCheckType
  formData.value.patSrc = queueVO?.patDetails.source
  getFreeRentInfo(formData.value)
  copyBarcode()
}
defineExpose({ setPatient }) // 提供 setPatient 方法，用于设置患者


const loading = ref(true) // 列表的加载中
const list = ref<JobRecordVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  jobType: [5, 30],
  docId: undefined,
  docName: undefined,
  devId: undefined,
  patId: undefined,
  patName: undefined,
  jobTime: [curDayStart(), curDayEnd()],
  summary: undefined,
  remark: undefined,
  createTime: []
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await JobRecordApi.getJobRecordDoctorPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const onRowClick = (cur) => {
  if (cur !== null)
    getSelectedRent( cur.rentId )
}

const getSelectedRent = async (rentId) => {
  formData.value = await DevRentApi.getDevRent(rentId)
}

const printBill = async (patId: string, checkType: number, printMode?: number) => {

  const curAppointment: AppointmentVO = await AppointmentApi.getCurAppointmentByPatIdAndCheckType( patId, checkType )
  console.info( curAppointment )

// 引入后使用示例
  hiprint.init({
    //    host: 'http://192.168.2.100:17521',
    token: '111111'
  });
// 下列方法都是没有拖拽设计页面的, 相当于代码模式, 使用代码设计页面
// 想要实现拖拽设计页面,请往下看 '自定义设计'
  var hiprintTemplate = new hiprint.PrintTemplate();  // 可传参数
  //var panel = hiprintTemplate.addPrintPanel({ width: 100, height: 130, paperFooter: 340, paperHeader: 10 }); 导致走三页
  var panel = hiprintTemplate.addPrintPanel({ width: 140, height: 130, paperNumberDisabled:true});
//文本
  const checkTypeName = checkTypeStore.getCheckTypeName(curAppointment.bookCheckType)
  panel.addPrintText({ options: { width: 140, height: 12, top: 2, left: 20, title: checkTypeName, textAlign: 'center', fontSize: 10, fontFamily: '微软雅黑',  fontWeight: '700', } });
  const patientBaisc = curAppointment.patName + "  " + calGender(curAppointment.patGender) + "  " + calculateAge(curAppointment.patBirthday) + "岁"
  panel.addPrintText({ options: { width: 140, height: 12, top: 16, left: 20, title: patientBaisc, textAlign: 'center' , fontSize: 10, fontFamily: '微软雅黑',  fontWeight: '700', } });
  const ward_bed = curAppointment.patWardDesc + "-" + curAppointment.patBedNo
  panel.addPrintText({ options: { width: 140, height: 12, top: 30, left: 20, title: ward_bed, textAlign: 'center', fontSize: 10, fontFamily: '微软雅黑',  fontWeight: '700', } });
  const bookTime = formatTimestamp(curAppointment.bookDate) + " " + getBookBeginTime(curAppointment.bookTimeslot)
  panel.addPrintText({ options: { width: 140, height: 12, top: 44, left: 20, title: bookTime, textAlign: 'center', fontSize: 10, fontFamily: '微软雅黑',  fontWeight: '700', } });
  panel.addPrintText({ options: { width: 140, height: 12, top: 58, left: 20, title: curAppointment.patId, textAlign: 'center', fontSize: 10, fontFamily: '微软雅黑',  fontWeight: '700', } });
  panel.addPrintText({ options: { width: 140, height: 12, top: 72, left: 20, title: curAppointment.patMobile, textAlign: 'center', fontSize: 10, fontFamily: '微软雅黑',  fontWeight: '700', } });
  //条形码
  panel.addPrintText({ options: { width: 140, height: 22, top: 86, left: 20, title: curAppointment.episodeId, textType: 'barcode' } });

//打印
  if (undefined === printMode)
    hiprintTemplate.print2([{},{},{}]); // 可以传 [定位参数]  http://https://ccsimple.github.io/sv-print-docs/config/template.html#%E8%87%AA%E5%AE%9A%E4%B9%89%E8%AE%BE%E8%AE%A1%E4%BD%BF%E7%94%A8%E7%A4%BA%E4%BE%8B
  else
    hiprintTemplate.print([{},{},{}]);
}
/* hiprint 示例
// 引入后使用示例
  hiprint.init({
    //    host: 'http://192.168.2.100:17521',
    token: '111111'
  });
// 下列方法都是没有拖拽设计页面的, 相当于代码模式, 使用代码设计页面
// 想要实现拖拽设计页面,请往下看 '自定义设计'
  var hiprintTemplate = new hiprint.PrintTemplate();  // 可传参数
  var panel = hiprintTemplate.addPrintPanel({ width: 100, height: 130, paperFooter: 340, paperHeader: 10 });
//文本
  panel.addPrintText({ options: { width: 140, height: 15, top: 20, left: 20, title: 'hiprint插件手动添加text', textAlign: 'center' } });
//条形码
  panel.addPrintText({ options: { width: 140, height: 35, top: 40, left: 20, title: '123456', textType: 'barcode' } });
//二维码
  panel.addPrintText({ options: { width: 35, height: 35, top: 40, left: 165, title: '123456', textType: 'qrcode' } });
//长文本
  panel.addPrintLongText({ options: { width: 180, height: 35, top: 90, left: 20, title: '长文本：hiprint是一个很好的webjs打印,浏览器在的地方他都可以运行' } });
//打印 直接打印
  hiprintTemplate.print2({}); // 可以传 [定位参数]  http://https://ccsimple.github.io/sv-print-docs/config/template.html#%E8%87%AA%E5%AE%9A%E4%B9%89%E8%AE%BE%E8%AE%A1%E4%BD%BF%E7%94%A8%E7%A4%BA%E4%BE%8B
*/
/* 分页打印
HiPrint.print({
  pages: [
    {
      text: 'Hello World!'
    },
    {
      html: '<div><h1>Hello World!</h1></div>',
      pageBreak: true
    },
    {
      image: 'image.png'
    }
  ]
});
*/

const getDevInfo = async () => {
  deviceInfo.value.category = ''
  deviceInfo.value.brand = ''
  deviceInfo.value.model = ''
  deviceInfo.value.state = 0
  if (isStringEmpty(formData.value.devId))
    return

  const data = await DeviceApi.getDeviceByDevId(formData.value.devId!)
  console.info( data )
  if ( null !== data)
    deviceInfo.value = data
}

const feeConfirm = async () => {
  const result = await DevRentApi.feeConfirm(formData.value.id)
  if (0 == result)
    message.success(t('操作成功'))
}

const feeCancel = async () => {
  const result = await DevRentApi.feeCancel(formData.value.id)
  if (0 == result)
    message.success(t('操作成功'))
}

const getDisplayBarcode = (): string => {
  if (!formData.value.checkType)
    return ""

  const displayBarcode: number[] = checkTypeStore.getCheckTypeDispBarCode(formData.value.checkType!)
  if (!displayBarcode.includes( formData.value.patSrc ))
    return ""

  return getBarcode()
}

const getBarcode = (): string => {
  if (!formData.value.checkType)
    return ""

  if (1 === formData.value.patSrc || 2 === formData.value.patSrc)
    return formData.value.applyNo??""
  else if (3 === formData.value.patSrc || 4 === formData.value.patSrc)
    return formData.value.episodeId??""

  return ""
}

const copyBarcode = async () => {
  displayBarCode.value = getDisplayBarcode()
  await navigator.clipboard.writeText( getBarcode() );
}

/** 初始化 **/
onMounted(() => {
  getList()
})

</script>

